# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '5795919': {  # dwc  qq
        'API_KEY': '2e416649e6ca0a1cbf9a1210cf4ce234',
        'gateway': 'http://pay.sufupay.vip/pay.html',
        'query_gateway': 'http://pay.sufupay.vip/query.html',
    },
    '6977160': {  # dwc jd
        'API_KEY': '13e1a5f5a722b29678b13c0099d20fdb',
        'gateway': 'http://pay.sufupay.vip/pay.html',
        'query_gateway': 'http://pay.sufupay.vip/query.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=' + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("sufupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 1 为网银支付
# "2 为微信支付
# 3 为支付宝支付"
# "5 为 QQ 钱包
# 6 为 JD 钱包
# 7为银联"
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '2'
    elif service == 'alipay':
        payType = '3'
    elif service == 'qq':
        payType = '5'
    elif service == 'quick':
        payType = '7'
    else:
        payType = '6'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('notify_url', '{}/pay/api/{}/sufupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('pay_type', _get_pay_type(service)),
        ('bank_code', 'qrCode'),
        ('merchant_code', mch_id),
        ('order_no', str(pay.id)),
        ('order_amount', str(pay_amount)),
        ('order_time', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('req_referer', settings.NOTIFY_PREFIX),
        ('customer_ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("sufupay create date: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(mch_id))
    _LOGGER.info("sufupay create html: %s", html_text)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("sufupay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['order_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('sufupay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['trade_status'])
    trade_no = data['trade_no']
    total_fee = float(data['order_amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0为成功 其余为失败
    if trade_status == 'success':
        _LOGGER.info('sufupay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'merchant_code': app_id,
        'order_no': str(pay_id),
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info(u'sufupay query: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['trade_status'])  # 0 订单未成功 1订单成功
        total_fee = float(data['order_amount'])
        trade_no = data['trade_no']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 'success':
            _LOGGER.info('sufupay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('sufupay data error, status_code: %s', response.status_code)
